/*
 * @Author: wangtao
 * @Date: 2021-02-18 11:21:01
 * @LastEditors: zeki mini
 * @LastEditTime: 2021-04-22 10:01:04
 * @Description: file content
 */
import React from 'react';
import {
  View,
  StyleSheet,
  SafeAreaView,
  ScrollView,
  NativeModules,
  Platform,
  BackHandler
} from 'react-native';
import {
  Button,
  msg,
} from '@/common';
import {
  mainBgColorLightGray,
  px2dp,
} from '@/styles';
import api from '@/api';
import { uploadImage } from '@/config';
import Picker from '../../../common/picker';
import ApplyForm from './components/apply-form';
import CertWrap from './components/cert-wrap';

const { Submit } = Button;

export default class InsuranceApplyForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      carType: '', // 选择的车辆类型
      carNo: '', // 车牌号
      engineNo: '', // 发动机号
      insureLinkMan: '', // 投保联系人
      insureLinkPhone: '', // 联系电话
      applicationNo: '', // 流水号
      carframeNo: '', //	车架号
      inCompanyId: '', //	所属公司ID
      inCompanyName: '', //	所属公司名称
      carOwnerType: { code: 1, name: '个人' }, // 车主类型
      carOwnerTypeOptions: [
        { code: 1, name: '个人' },
        { code: 2, name: '法人' },
      ], // 车主类型
      carOwnerName: '', // 车主名称
      drivingFrontUrl: '', // 行驶证正面url
      drivingAnnexUrl: '', // 行驶证背面url
      licenseUrl: '', // 营业执照url
      idCardFrontUrl: '', // 身份证正面url
      idCardAnnexUrl: '', // 身份证背面url
      allCompanyOptions: [], // 物流公司选项
    };
  }

  componentDidMount() {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const {
      applicationNo,
    } = params;
    this.setState({
      applicationNo,
    });

    this.preApplicationInsurance(applicationNo);
    this.getAllCompany();
    // 处理安卓物理返回键
    if (Platform.OS == 'android') {
      BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
    }
  }

  componentWillUnmount() {
    if (Platform.OS === 'android') {
      BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
    }
  }

  onBackAndroid = () => {
    Picker.hide();
    msg.emit('router: back');
    return true;
  };

  render() {
    const {
      carNo,
      engineNo,
      carType,
      insureLinkMan,
      insureLinkPhone,
      applicationNo,
      carOwnerTypeOptions,
      carOwnerType,
      inCompanyName,
      allCompanyOptions,
      carOwnerName,
      drivingFrontUrl,
      drivingAnnexUrl,
      licenseUrl,
      idCardFrontUrl,
      idCardAnnexUrl,
      carframeNo,
    } = this.state;
    return (
      <SafeAreaView style={{ flex: 1 }}>
        <View style={styles.container}>
          <ScrollView
            contentContainerStyle={styles.scrollContainer}
            showsVerticalScrollIndicator={false}
          >
            <ApplyForm
              carNo={carNo}
              engineNo={engineNo}
              carType={carType}
              insureLinkMan={insureLinkMan}
              insureLinkPhone={insureLinkPhone}
              applicationNo={applicationNo}
              carOwnerTypeOptions={carOwnerTypeOptions}
              carOwnerType={carOwnerType}
              inCompanyName={inCompanyName}
              allCompanyOptions={allCompanyOptions}
              carOwnerName={carOwnerName}
              carframeNo={carframeNo}
              showPicker={this.showPicker}
              onChange={this.onChange}
            />
            <CertWrap
              carOwnerType={carOwnerType}
              selectImg={this.selectImg}
              drivingFrontUrl={drivingFrontUrl}
              drivingAnnexUrl={drivingAnnexUrl}
              licenseUrl={licenseUrl}
              idCardFrontUrl={idCardFrontUrl}
              idCardAnnexUrl={idCardAnnexUrl}
              onChange={this.onChange}
            />

            <Submit
              text='提交'
              boxStyle={{
                width: px2dp(640),
                height: px2dp(96),
                borderRadius: px2dp(12),
                overflow: 'hidden',
                marginTop: px2dp(32),
              }}
              btnStyle={{}}
              btnTextStyle={{
                fontSize: px2dp(36),
              }}
              onClick={() => {
                this.applicationInsuranceUpdate();
              }}
            />
          </ScrollView>
        </View>
      </SafeAreaView>
    );
  }

  // 选择照片
  selectImg = (type) => {
    NativeModules.DataModule.chooseImageOrVideo(
      (path, imageBase64, resType, mimeName) => {
        this.uploadImage(type, path, imageBase64, resType, mimeName);
      },
    );
  };

  // 上传照片upload?dirName=refundMark
  uploadImage(type, path, imageBase64, resType, mimeName) {
    uploadImage('upload?dirName=insurance', path)
      .then((res) => {
        // 请求成功
        if (res.success) {
          const { url, localFileName } = res.data;
          this.setState({ [type]: url });
        } else {
          msg.emit('app:tip', { text: res.msg });
        }
      })
      .catch((err) => {
        // 请求失败
        msg.emit('app:tip', { text: '上传出错，请重试' });
      });
  }

  // 申请
  applicationInsuranceUpdate = () => {
    const {
      applicationNo,
      carOwnerType,
      inCompanyName,
      carframeNo,
      carOwnerName,
      drivingFrontUrl,
      drivingAnnexUrl,
      licenseUrl,
      idCardFrontUrl,
      idCardAnnexUrl,
      inCompanyId,
    } = this.state;

    if (!carframeNo) {
      msg.emit('app:tip', { text: '车架号必填' });
      return;
    }
    if (!inCompanyId) {
      msg.emit('app:tip', { text: '所属公司必填' });
      return;
    }
    if (!carOwnerName) {
      msg.emit('app:tip', { text: '车主名称必填' });
      return;
    }
    if (!drivingFrontUrl) {
      msg.emit('app:tip', { text: '行驶证正面必传' });
      return;
    }
    if (!drivingAnnexUrl) {
      msg.emit('app:tip', { text: '行驶证背面必传' });
      return;
    }
    if (carOwnerType.code == 1) {
      if (!idCardFrontUrl) {
        msg.emit('app:tip', { text: '身份证正面必传' });
        return;
      }
      if (!idCardAnnexUrl) {
        msg.emit('app:tip', { text: '身份证背面必传' });
        return;
      }
    }
    if (carOwnerType.code == 2) {
      if (!licenseUrl[0]) {
        msg.emit('app:tip', { text: '营业执照必传' });
        return;
      }
    }

    let params = {
      applicationNo,
      carOwnerName,
      carOwnerType,
      carframeNo,
      drivingFrontUrl,
      drivingAnnexUrl,
      inCompanyName,
      inCompanyId,
    };
    if (carOwnerType.code == 1) {
      params.idCardFrontUrl = idCardFrontUrl;
      params.idCardAnnexUrl = idCardAnnexUrl;
    }
    if (carOwnerType.code == 2) {
      params.licenseUrl = licenseUrl;
    }

    api.insurance.applicationInsuranceUpdate(params).then((res) => {
      if (res.success) {
        msg.emit('router: goToNext', {
          routeName: 'InsuranceFeedBack',
          status: 1,
          headerTitle: '提交结果',
          title: '您的申请提交成功',
          desc:
            '您的报价申请提交成功，我们会尽快安排客服人员与您联系，请随时保持电话畅通！',
          routerFrom: 'InsuranceApplyForm',
          id: res.data,
        });
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    });
  };

  // 查看预申请的信息
  preApplicationInsurance = (applicationNo) => {
    api.insurance.preApplicationInsurance(applicationNo).then((res) => {
      if (res.success) {
        const {
          carNo,
          carType,
          insureLinkMan,
          insureLinkPhone,
          applicationNo,
          engineNo,
        } = res.data;
        this.setState({
          carNo,
          carType: carType && carType.name,
          insureLinkMan,
          insureLinkPhone,
          applicationNo,
          engineNo,
        });
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    });
  };

  // 所有的物流公司
  getAllCompany = () => {
    api.insurance.getAllCompany().then((res) => {
      if (res.success) {
        this.setState({ allCompanyOptions: res.data });
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    });
  };

  showPicker = (title, dataList, pickerType) => {
    const {
      carOwnerTypeOptions,
      carOwnerType,
      inCompanyName,
      allCompanyOptions,
    } = this.state;
    let options; let
      selectVal;
    if (pickerType == 'carOwnerType') {
      options = dataList.map((item) => {
        return item.name;
      });
      selectVal = carOwnerType.name;
    }
    if (pickerType == 'inCompanyName') {
      options = dataList.map((item) => {
        return item.name;
      });
      selectVal = inCompanyName;
    }
    selectVal = selectVal || options[0];
    Picker.init({
      pickerTitleText: title,
      pickerCancelBtnText: '取消',
      pickerConfirmBtnColor: [186, 145, 74, 1],
      pickerCancelBtnColor: [102, 101, 100, 1],
      pickerConfirmBtnText: '确定',
      selectedValue: [selectVal],
      pickerBg: [255, 255, 255, 1],
      pickerToolBarBg: [255, 255, 255, 1],
      pickerFontColor: [186, 145, 74, 1],
      pickerRowHeight: 40,
      pickerData: options,
      onPickerConfirm: (pickedValue, pickedIndex) => {
        console.log(
          '🚀🚀🚀wimi======>>>pickedValue, pickedIndex',
          pickedValue,
          pickedIndex,
        );
        if (pickerType == 'carOwnerType') {
          const carOwnerTypeObj = carOwnerTypeOptions.find((item) => {
            if (item.name == pickedValue[0]) {
              return true;
            }
          });
          this.setState({ carOwnerType: carOwnerTypeObj });
        }
        if (pickerType == 'inCompanyName') {
          const inCompanyNameObj = allCompanyOptions.find((item) => {
            if (item.name == pickedValue[0]) {
              return true;
            }
          });
          this.setState({
            inCompanyName: inCompanyNameObj.name,
            inCompanyId: inCompanyNameObj.code,
          });
        }
      },
      onPickerCancel: (pickedValue, pickedIndex) => {},
      onPickerSelect: (pickedValue, pickedIndex) => {},
    });
    Picker.show();
  };

  onChange = (key, val) => {
    this.setState({ [key]: val });
  };
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: mainBgColorLightGray,
    alignItems: 'center',
  },
  scrollContainer: {
    alignItems: 'center',
    paddingBottom: px2dp(80),
  },
});
